package com.h117121.fashionshop.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.h117121.fashionshop.controller.generic.GenericController;
import com.h117121.fashionshop.core.dom.Account;
import com.h117121.fashionshop.core.exception.UsernameExistException;
import com.h117121.fashionshop.validator.RegisterValidator;

@Controller
@RequestMapping("/register")
public class RegisterController extends GenericController {
	@Autowired
	private RegisterValidator validator;

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, true));
	}

	@RequestMapping(method = RequestMethod.GET)
	public String showPage(ModelMap model) {
		model.addAttribute("registerAcc", new Account());
		return "RegisterPage";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String processFormSubmit(
			@ModelAttribute("registerAcc") Account account, BindingResult errors) {
		validator.validate(account, errors);
		if (errors.hasErrors()) {
			return "RegisterPage";
		}

		try {
			businessService.register(account);
			return "RegisterSuccessPage";
		} catch (UsernameExistException ex) {
			errors.rejectValue("userName", "existed.userName",
					"Tên đăng nhập đã tồn tại");
			return "RegisterPage";
		}
	}
}
